package com.hanxiaozhang.system.service.impl;

import com.hanxiaozhang.exception.UserNotLoginException;
import com.hanxiaozhang.security.CurrentUser;
import com.hanxiaozhang.system.dao.MenuDao;
import com.hanxiaozhang.system.dao.UserDao;
import com.hanxiaozhang.system.entity.UserEntity;
import com.hanxiaozhang.util.StringUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 功能描述: <br>
 * 〈〉
 *
 * @Author:hanxiaozhang
 * @Date: 2020/7/27
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserDao userDao;

    @Resource
    private MenuDao menuDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserEntity user = userDao.getByUsername(username);
        if (user == null) {
            throw new UserNotLoginException("用户名不存在!");
        }
        List<String> permission = menuDao.listPermsByUserId(user.getUserId());
        // 权限
        Set<GrantedAuthority> authorities = permission
                .stream().filter(StringUtil::isNotBlank).map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
        return new CurrentUser(username, user.getPassword(), user.getUserId(), user.getName(),authorities);
    }

}
